import React from "react";
import Dialog from "../components/dialog";
import * as ReactDOM from "react-dom";

/**
 * dialog构建工具
 */
export default class DialogBuilder {
    constructor(content){
        this.content = content;
        this.btns = [];
        this.dialogTitle = "提示";
        this.closeable = true;
        this.className = "";
        this.styleObj = {};
    }

    /**
     * 设置标题
     * @param title 标题
     */
    title(title){
        this.dialogTitle = title;
        return this;
    }

    /**
     * 设置样式
     */
    style(style){
        this.styleObj = Object.assign(this.styleObj, style);
        return this;
    }

    /**
     * 较大的modal
     */
    bigModal(){
        this.className += " modal-lg";
        return this;
    }

    /**
     * 较小的modal
     */
    smallModal(){
        this.className += " modal-sm";
        return this;
    }

    /**
     * 纵向居中的modal
     */
    verticallyCenter(){
        this.className += " modal-dialog-centered";
        return this;
    }

    /**
     * 添加按钮
     * @param title 按钮标题
     * @param callback 单击回调
     * @param closable 可否关闭
     * @param className 按钮样式类
     */
    btn(title, callback, closable = true, className = "btn-primary"){
        this.btns.push({title: title, callback: callback, closable: closable, className: className});
        return this;
    }

    /**
     * 关闭事件
     * @param callback
     */
    onClose(callback){
        this.dialogCloseHandler = callback;
    }

    /**
     * 构建并显示
     */
    show(){
        let dialogBox = document.createElement("div");
        document.body.appendChild(dialogBox);
        ReactDOM.render(
            <Dialog
                onClose={this.dialogCloseHandler}
                title={this.dialogTitle}
                btns={this.btns}
                content={this.content}
                closable={this.closeable}
                display={true}
                className={this.className}
                style={this.styleObj}
            />,
            dialogBox);
        return dialogBox;
    }

    /**
     * 显示对话框，并在关闭时删除Element
     * @return {HTMLElement}
     */
    removeOnClose(){
        let dialogBox = document.createElement("div");
        document.body.appendChild(dialogBox);
        //重写关闭事件
        let closeCallback = this.dialogCloseHandler;
        this.dialogCloseHandler = ()=>{
            dialogBox.remove();
            if(closeCallback instanceof Function)
                closeCallback();
            ReactDOM.unmountComponentAtNode(dialogBox);
        };
        ReactDOM.render(
            <Dialog
                onClose={this.dialogCloseHandler}
                title={this.dialogTitle}
                btns={this.btns}
                content={this.content}
                closable={this.closeable}
                display={true}
                className={this.className}
                style={this.styleObj}
            />,
            dialogBox);
        return dialogBox;
    }
}
